package no.saiboten.tourbuilder.user.controller;

import no.saiboten.tourbuilder.user.User;
import no.saiboten.tourbuilder.user.UserDAO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user/admin")
public class UserAdminController {

	@Autowired
	private UserDAO userDAO;

	@RequestMapping(method = RequestMethod.GET)
	public @ModelAttribute("user")
	ModelAndView getUser() {
		ModelAndView mav = new ModelAndView("user/useradmin");
		mav.addObject("users", userDAO.getAllUsers());
		return mav;
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public ModelAndView createUser(@ModelAttribute("user") User user,
			BindingResult bindingResult) {
		ModelAndView mav = new ModelAndView("user/useradmin");
		if (userDAO.insertUser(user)) {
			mav.addObject("result", "User created!");
		} else {
			mav.addObject("result", "Could not create user..");
		}
		return mav;
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ModelAndView updateUser(@ModelAttribute("useradmin") User user,
			BindingResult bindingResult) {
		ModelAndView mav = new ModelAndView("user/user");
		if (userDAO.updateUser(user)) {
			mav.addObject("result", "Updated user!");
		} else {
			mav.addObject("result", "Could not update user.");
		}
		return mav;
	}

	@RequestMapping(value = "/delete/{userid}", method = RequestMethod.POST)
	public ModelAndView deleteUser(@PathVariable String userid) {
		ModelAndView mav = new ModelAndView("user/useradmin");
		if (userDAO.deleteUser(userid)) {
			mav.addObject("result", "User deleted");
		} else {
			mav.addObject("result", "Could not delete user");
		}
		return mav;
	}
}
